<template>
  <div class="line-chart" ref="lineChartRef"></div>
</template>
<script setup>
import { ref, onMounted, inject, watch } from 'vue';

const props = defineProps({
  data: {
    type: Array,
    default: () => [],
  },
  visibleData: {
    type: Array,
    default: () => [],
  },
});

const lineChartRef = ref(null);
const timer = ref();
const Echarts = inject('$echarts');

const initEchartsOneFn = () => {
  const myChart = Echarts.init(lineChartRef.value);
  const option = {
    tooltip: {
      //默认显示tooltip
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#f7f9fd',
          color: '#333',
        },
      },
      backgroundColor: '#f7f9fd',
      borderColor: '#B5CFFF',
      borderWidth: 1,
      borderRadius: 6,
      textStyle: {
        color: '#000',
        fontWeight: 'bold',
        fontSize: 14,
      },
      formatter: (params) => {
        return params[0].name + ' 分' + '<br>' + params[0].value + ' 人';
      },
    },
    grid: {
      top: '14%',
      left: '0%',
      right: '13%',
      bottom: '0%',
      containLabel: true,
    },
    xAxis: {
      name: '人数',
      type: 'value',
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        formatter: '{value}',
      },
      splitLine: {
        show: false,
      },
    },
    yAxis: {
      name: '分数',
      type: 'category',
      splitLine: {
        show: true,
      },
      axisLine: {
        onZero: false,
        show: true,
      },
      axisLabel: {
        formatter: '{value}',
      },
      boundaryGap: false,
      //data取props.data的value
      data: props.data.map((item) => item.name),
    },
    series: [
      {
        type: 'line',
        data: props.data,
        areaStyle: {
          color: 'rgba(11, 110, 255,0.2)',
        },
        lineStyle: { width: 0 },
        showSymbol: false,
        silent: true,
        z: 1,
        smooth: true,
      },
      {
        type: 'line',
        data: props.data,
        areaStyle: null,
        showAllSymbol: true,
        symbolSize: function (value, data) {
          return props.visibleData.includes(+data.name) ? 10 : 0;
        },
        symbol: 'circle',
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 2,
          color: '#0b6eff',
        },
        lineStyle: {
          width: 2,
          shadowColor: 'rgba(0,0,0,0.1)',
          shadowBlur: 6,
          shadowOffsetY: 4,
        },
        z: 2,
        smooth: true,
      },
    ],
  };

  myChart.setOption(option);
  window.addEventListener('resize', function () {
    myChart.resize();
  });
};

// 监听分数、省份、科目变化
watch(
  [() => props.data],
  () => {
    initEchartsOneFn();
  },
  {
    deep: true,
  }
);

onMounted(() => {
  initEchartsOneFn();
});
</script>

<style scoped lang="scss">
.line-chart {
  width: 507px;
  height: 370px;
}
</style>
